package com.azt.provider.impl;

import com.azt.api.dto.member.MemberExt;
import com.azt.api.dto.member.MemberParam;
import com.azt.api.pojo.CenCollection;
import com.azt.api.pojo.Member;
import com.azt.api.pojo.MemberDetail;
import com.azt.api.service.MemberService;
import com.azt.model.page.Pagination;
import com.azt.model.page.TPagination;
import com.azt.provider.mapper.CenCollectionMapper;
import com.azt.provider.mapper.MemberDetailMapper;
import com.azt.provider.mapper.MemberMapper;
import com.azt.utils.MathUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MemberServiceImpl implements MemberService {
	
	@Autowired
	private MemberMapper memberMapper;
	
	@Autowired
	private MemberDetailMapper memberDetailMapper;
	
	@Autowired
	private CenCollectionMapper cenCollectionMapper;
	
	@Override
	public Pagination selectMemberList(int pageno, int pagesize,Map<String, String> params) {
		Page<Object> startPage = PageHelper.startPage(pageno, pagesize);
		List<Member> memberList=memberMapper.selectMemberList(params);
		for(Member member : memberList) {
			member.setShPrice(getTotalPayPrice(1, member.getCompanyId(), member.getSignintime(), DateUtil.offsetDay(member.getEndtime(), 1)));
			member.setXjPrice(getTotalPayPrice(2, member.getCompanyId(), member.getSignintime(), DateUtil.offsetDay(member.getEndtime(), 1)));
		}
		Pagination p = new Pagination(startPage, memberList);
		p.setList(memberList);
		p.setParams(params);
		return p;
	}

	@Override
	public void saveMember(Member member) {
		 memberMapper.insertSelective(member);
		
	}

	@Override
	public Member selectMemberByid(Integer id) {
		return  memberMapper.selectMemberOne(id);
	}

	@Override
	public void addMemberDetailList(MemberDetail[] memberDetailArr) {
		 Integer memberid=memberDetailArr[0].getCenMemberId();
		 if(memberid!=null){
			 MemberDetail m=new MemberDetail();
			 m.setCenMemberId(memberid);
			 memberDetailMapper.delete(m);
		 }
		 for (int i = 0; i < memberDetailArr.length; i++) {
			 Date d=new Date();
			 MemberDetail m=memberDetailArr[i];
			 m.setCreatetime(d);
			 m.setUpdatetime(d);
			 memberDetailMapper.insertSelective(m);
		 }
	}

	@Override
	public List<MemberDetail> selectMemberDetailsBymid(Integer mid) {
		MemberDetail md=new MemberDetail();
		md.setCenMemberId(mid);
		return memberDetailMapper.select(md);
	}

	@Override
	public List<MemberDetail> findMyMemberDetail(int memberId) {
		return memberDetailMapper.findMyMemberDetail(memberId);
	}

	@Override
	public Member selectMemberByCompanyId(String startdate,String mid) {
		  return memberMapper.selectValidateMem(startdate, mid);
	}

	@Override
	public Pagination selectCenCollectionList(int pageno, int pagesize, Map<String, String> params) {
		Page<Object> startPage = PageHelper.startPage(pageno, pagesize);
		List<CenCollection> cenMemberList=cenCollectionMapper.selectCenCollectionList();
		Pagination p = new Pagination(startPage, cenMemberList);
		p.setList(cenMemberList);
		p.setParams(params);
		return p;
	}

	

	public List<Map> searchMemberProduct(Map param) {
		return memberMapper.searchMemberProduct(param);
	}

	@Override
	public Member getCenMember(int companyId) {
		Member member = new Member();
		member.setCompanyId(companyId);
		member.setRemoved(0);
		member.setState(1);
		Example example = new Example(Member.class);
		example.createCriteria().andEqualTo(member).andLessThanOrEqualTo("signintime", DateUtil.today()).andGreaterThanOrEqualTo("endtime", DateUtil.today());
		List<Member> list = memberMapper.selectByExample(example);
		return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
	}

	@Override
	public List<CenCollection> findCollectionByMember(int memberId) {
		CenCollection cenCollection = new CenCollection();
		cenCollection.setCenMemberId(memberId);
		Example example = new Example(CenCollection.class);
		example.createCriteria().andEqualTo(cenCollection);
		example.orderBy("stage").desc();
		return cenCollectionMapper.selectByExample(example);
	}

	@Override
	public void calcMemberCollection(int companyId) {
		//判断供应商是否是集采供应商
		Member member = getCenMember(companyId);
		if(member == null) {
			return;
		}
		PageHelper.orderBy("stage desc");
		List<MemberDetail> memberDetailList = selectMemberDetailsBymid(member.getId());		//返点规则
		if(CollectionUtil.isEmpty(memberDetailList)) {
			return;
		}

		//获取集采供应商有效期内的所有已支付的金额
		double payedPrice = memberMapper.getPayedPrice(companyId, member.getSignintime(), DateUtil.offsetDay(member.getEndtime(), 1));

		//返点记录
		List<CenCollection> cenCollectionList = findCollectionByMember(member.getId());

		//可以达到哪个返点阶段
		MemberDetail reachedDetail = null;
		for(MemberDetail memberDetail : memberDetailList) {
			if(payedPrice >= memberDetail.getMaxNum().doubleValue()) {
				reachedDetail = memberDetail;
				break;
			}
		}

		if(reachedDetail == null) {
			return;
		}
		//该订单从哪个阶段开始返点
		int stage = CollectionUtil.isNotEmpty(cenCollectionList) ? cenCollectionList.get(0).getStage() + 1 : 1;
		//开始返点
		for(int i = stage; i <= reachedDetail.getStage(); i++) {
			//返点规则
			MemberDetail detail = getDetailInList(memberDetailList, i);
			if(detail == null) {
				continue;
			}
			//返点金额 :（规则最大值-最小值） * 返点比例
			double amount = MathUtil.round(MathUtil.multiply(MathUtil.subtract(detail.getMaxNum(), detail.getMinNum()), detail.getPointPercent() * 0.01), 2);
			CenCollection cenCollection = new CenCollection();
			cenCollection.setCenMemberId(member.getId());
			cenCollection.setCompanyId(companyId);
			cenCollection.setStage(i);
			cenCollection.setAmount(amount);
			cenCollection.setState(0);		//待收款
			cenCollectionMapper.insertSelective(cenCollection);
		}
	}

	@Override
	public TPagination<MemberExt> geteMembersByParam(MemberParam param) {
		return null;
	}

	@Override
	public TPagination<MemberExt> getMembersExtByParam(MemberParam param) {
		Page<Object> startPage = PageHelper.startPage(param.getPageNo(), param.getPageSize());
		List<MemberExt> memberExts = memberMapper.getMembersExtByParam(param);
		TPagination<MemberExt> p = new TPagination(startPage, memberExts);
		return p;
	}

	private MemberDetail getDetailInList(List<MemberDetail> list, int stage) {
		for(MemberDetail detail : list) {
			if(detail.getStage().intValue() == stage) {
				return detail;
			}
		}
		return null;
	}

	@Override
	public void updateCenCollection(CenCollection collection, List<CenCollection> collectionList) {
		if(collection!=null){
			cenCollectionMapper.updateByPrimaryKeySelective(collection);
		}else{
			if(collectionList!=null && collectionList.size()>0){
				for (int i = 0; i < collectionList.size(); i++) {
					cenCollectionMapper.updateByPrimaryKeySelective(collectionList.get(i));
				}
			}
		}
	}
	
	@Override
	public List<CenCollection> getMingXiCollection(int memberId, Integer state) {
		return cenCollectionMapper.getMingXiCollection(memberId, state);
	}


	@Override
	public void updateCenMember(Member member) {
		memberMapper.updateByPrimaryKeySelective(member);
		
	}

	@Override
	public Double getTotalPayPrice(int orderType, int sellerCompanyId, Date sdate, Date edate) {
		 return memberMapper.getTotalPayPrice(orderType, sellerCompanyId, sdate, edate);
	}

	@Override
	public CenCollection selectEnqCollection(Integer state, Integer memberId) {
		return  cenCollectionMapper.selectEnqCollection(state, memberId);
	}

	@Override
	public Member getSignMemberByCompanyId(Integer companyId) {
		return memberMapper.getSignMemberByCompanyId(companyId);
	}

	@Override
	public int getReachedStage(int memberId) {
		CenCollection collection = new CenCollection();
		collection.setCenMemberId(memberId);
		return cenCollectionMapper.selectCount(collection);
	}

}
